package ch.ethz.smseth;

import java.util.Collections;
import java.util.HashMap;
import java.util.Map;

import android.app.Activity;
import android.app.PendingIntent;
import android.content.Context;
import android.content.Intent;
import android.telephony.gsm.SmsManager;

public class PhoneSender
{
	public static final String EXTRA_ID = "ID";
	
	private Context _ctx;
	private static int _counter = 0;
	private static Map<Integer, Integer> _resultCodes = Collections.synchronizedMap(new HashMap<Integer, Integer>());
	
	public PhoneSender(Context ctx)
	{
		_ctx = ctx;
	}
	
	public void send(String destination, String message) throws SenderException
	{
		Intent sentIntent = new Intent(_ctx, SentBroadcastReceiver.class);
		int id = _counter ++;
		sentIntent.putExtra(EXTRA_ID, id);
		
		PendingIntent pending = PendingIntent.getBroadcast(_ctx, 0, sentIntent, PendingIntent.FLAG_ONE_SHOT);
		try
		{
			SmsManager manager = SmsManager.getDefault();
			manager.sendTextMessage(destination, null, message, pending, null);
		}
		catch (NullPointerException e)
		{
			throw new SenderException("Lost connection.");
		}
		
		do
		{
			try
			{
				Thread.sleep(500);
			}
			catch(InterruptedException e)
			{
				// should not occur
			}
		} while (!_resultCodes.containsKey(id));
		
		int resultCode = _resultCodes.remove(id);
		if (resultCode == Activity.RESULT_OK) return;
		if (resultCode == SmsManager.RESULT_ERROR_GENERIC_FAILURE) throw new SenderException("Generic SMS Service failure.");
		if (resultCode == SmsManager.RESULT_ERROR_RADIO_OFF) throw new SenderException("Radio is off.");
		if (resultCode == SmsManager.RESULT_ERROR_NULL_PDU) throw new SenderException("No PDU.");
		if (resultCode == SmsManager.RESULT_ERROR_NO_SERVICE) throw new SenderException("No Service.");
		
		throw new SenderException("Unknown result code.");
	}
	
	public static void putResultCode(int id, int resultCode)
	{
		_resultCodes.put(id, resultCode);
	}
}
